package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {

    //1.1 保存或修改BaseMapper方式,需要加@Mapper
    @Autowired
    private ApartmentInfoMapper apartmentInfoMapper;
    @Autowired
    private FacilityInfoMapper facilityInfoMapper;
    @Autowired
    private LabelInfoMapper labelInfoMapper;
    @Autowired
    private FeeValueMapper feeValueMapper;
    @Autowired
    private GraphInfoMapper graphInfoMapper;

    @Autowired
    private ApartmentFacilityService apartmentFacilityService;
    @Autowired
    private ApartmentLabelService apartmentLabelService;
    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService;
    @Autowired
    private GraphInfoService graphInfoService;

    @Autowired
    private ProvinceInfoService provinceInfoService;
    @Autowired
    private CityInfoService cityInfoService;
    @Autowired
    private DistrictInfoServiceImpl districtInfoService;

    @Autowired
    private RoomInfoService roomInfoService;

    //保存或修改公寓信息
    @Override
    public void customSaveOrUpdateApartment(ApartmentSubmitVo apartmentSubmitVo) {
        //6.5 由于MyBatisPlus的回填机制,id会被回填,导致增加操作时,getId不为空,所以getId放在saveOrUpdate之前
        Long apartmentId = apartmentSubmitVo.getId();

        //7 增加省市区Name,要加在基本信息saveOrUpdate之前,否则无法赋值,
        //  因为后赋值的话虽然对象(java)赋值上了,但是后续并没有再次saveOrUpdate,导致公寓表(MySQL)的三个name并没有被同步,
        //  虽然后面操作数据库了,但是操作的不是公寓表,只是其它中间表
        Long provinceId = apartmentSubmitVo.getProvinceId();
        String provinceName = provinceInfoService.getById(provinceId).getName();
        apartmentSubmitVo.setProvinceName(provinceName);

        Long cityId = apartmentSubmitVo.getCityId();
        String cityName = cityInfoService.getById(cityId).getName();
        apartmentSubmitVo.setCityName(cityName);

        Long districtId = apartmentSubmitVo.getDistrictId();
        String districtName = districtInfoService.getById(districtId).getName();
        apartmentSubmitVo.setDistrictName(districtName);


        //1 添加/修改公寓基本信息 apartment_info
        //1 多态,这里将子类对象赋给父类引用,父类引用能获取到自己的属性
        //1.1 BaseMapper方式
        //apartmentInfoMapper.insert(apartmentSubmitVo);
        //1.2 ServiceImpl方式,底层也是调用了BaseMapper的insert方法;
        // this对象的泛型是父类对象而非子类对象,所以可以直接this.save(),而传参是多态
        //this.save(apartmentSubmitVo);
        //1.3 改save为saveOrUpdate,apartment_info的修改可以直接放到saveOrUpdate中
        this.saveOrUpdate(apartmentSubmitVo);

        //修改时,先删除,请求参数eg: [1,2,3,4,5]->[2,5,9,10]
        //6 删除该公寓的所有配套、标签、杂费、图片信息
        if (apartmentId != null) {
            //6.1 配套
            LambdaQueryWrapper<ApartmentFacility> facilityWrapper = new LambdaQueryWrapper<>();
            facilityWrapper.eq(ApartmentFacility::getApartmentId, apartmentId);
            apartmentFacilityService.remove(facilityWrapper);
            //6.2 标签
            LambdaQueryWrapper<ApartmentLabel> labelWrapper = new LambdaQueryWrapper<>();
            labelWrapper.eq(ApartmentLabel::getApartmentId, apartmentId);
            apartmentLabelService.remove(labelWrapper);
            //6.3 杂费
            LambdaQueryWrapper<ApartmentFeeValue> feeValueWrapper = new LambdaQueryWrapper<>();
            feeValueWrapper.eq(ApartmentFeeValue::getApartmentId, apartmentId);
            apartmentFeeValueService.remove(feeValueWrapper);
            //6.4图片
            LambdaQueryWrapper<GraphInfo> graphInfoWrapper = new LambdaQueryWrapper<>();
            graphInfoWrapper.eq(GraphInfo::getItemId, apartmentId);
            graphInfoWrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT);
            graphInfoService.remove(graphInfoWrapper);
        }

        //!!!!!!!!!要重新将公寓id赋值,否则后面用的apartmentId变量是null,导致中间表的apartment_id字段是null!!!!!!!!!
        apartmentId = apartmentSubmitVo.getId();

        //2 添加公寓配套信息 apartment_facility
        //2.1 获取该公寓的所有配套id
        List<Long> facilityInfoIds = apartmentSubmitVo.getFacilityInfoIds();
        //2.2 判断配套id集合是否为空,不为空则向表中添加数据
        if (!CollectionUtils.isEmpty(facilityInfoIds)) {
            //2.3 遍历配套id集合,将Long型的id转为apartmentFacility对象,并保存到数据库
            //优化:传入指定大小,因为每次请求中间表/关联表集合大小是确定的
            ArrayList<ApartmentFacility> apartmentFacilityArrayList = new ArrayList<>(facilityInfoIds.size());
            System.out.println("增加配套信息");
            for (Long fid : facilityInfoIds) {
                //2.4 向中间表apartment_facility中的字段set值
                ApartmentFacility apartmentFacility = ApartmentFacility.builder()
                    //2.5 如果是添加操作正常情况apartmentSubmitVo.getId()==null,
                    // 而这里不为空是因为MyBatisPlus会将id回填给apartmentSubmitVo对象
                    .apartmentId(apartmentId)
                    .facilityId(fid)
                    .build();
                apartmentFacilityArrayList.add(apartmentFacility);
            }
            //2.6 将中间表apartment_facility的数据放到集合中,然后批量添加
            System.out.println(apartmentFacilityService.saveBatch(apartmentFacilityArrayList) + "-----efedf----");
        }

        //3 添加公寓标签信息 apartment_label
        List<Long> labelIds = apartmentSubmitVo.getLabelIds();
        if (!CollectionUtils.isEmpty(labelIds)) {
            ArrayList<ApartmentLabel> apartmentLabelArrayList = new ArrayList<>(labelIds.size());
            for (Long lid : labelIds) {
                ApartmentLabel apartmentLabel = ApartmentLabel.builder().build();
                apartmentLabel.setApartmentId(apartmentId);
                apartmentLabel.setLabelId(lid);
                apartmentLabelArrayList.add(apartmentLabel);
            }
            apartmentLabelService.saveBatch(apartmentLabelArrayList);
        }

        //4 添加公寓杂费信息 apartment_fee_value
        List<Long> feeValueIds = apartmentSubmitVo.getFeeValueIds();
        if (!CollectionUtils.isEmpty(feeValueIds)) {
            ArrayList<ApartmentFeeValue> apartmentFeeValueArrayList = new ArrayList<>(feeValueIds.size());
            for (Long fid : feeValueIds) {
                ApartmentFeeValue apartmentFeeValue = ApartmentFeeValue.builder().build();
                apartmentFeeValue.setApartmentId(apartmentId);
                apartmentFeeValue.setFeeValueId(fid);
                apartmentFeeValueArrayList.add(apartmentFeeValue);
            }
            apartmentFeeValueService.saveBatch(apartmentFeeValueArrayList);
        }

        //5 添加公寓图片信息 graph_info 不是多对多而是一对多,所以不用中间表
        List<GraphVo> graphVoList = apartmentSubmitVo.getGraphVoList();
        if (!CollectionUtils.isEmpty(graphVoList)) {
            ArrayList<GraphInfo> graphInfoList = new ArrayList<>(graphVoList.size());
            for (GraphVo graphVo : graphVoList) {
                GraphInfo graphInfo = new GraphInfo();
                graphInfo.setName(graphVo.getName());
                graphInfo.setUrl(graphVo.getUrl());
                graphInfo.setItemType(ItemType.APARTMENT);
                graphInfo.setItemId(apartmentId);
                graphInfoList.add(graphInfo);
            }
            graphInfoService.saveBatch(graphInfoList);
        }
    }

    //查询公寓详情信息
    //一条SQL多表联查
    @Override
    public ApartmentDetailVo customGetApartmentDetailById(Long id) {
        return apartmentInfoMapper.customSelectById(id);
    }
    //多次查询,将结果放到ApartmentDetailVo中
    public ApartmentDetailVo customGetApartmentDetailById2(Long id) {
        ApartmentDetailVo apartmentDetailVo = new ApartmentDetailVo();
        //1. 将基本信息封装到响应VO对象中
        ApartmentInfo apartmentInfo = apartmentInfoMapper.selectById(id);
        BeanUtils.copyProperties(apartmentInfo,apartmentDetailVo);

        //2. 查询配套信息并放到VO对象中
        List<FacilityInfo> facilityInfoList = facilityInfoMapper.findFacilityListByApartmentId(id);


        return apartmentDetailVo;
    }

    //多条件分页查询公寓信息
    @Override
    public void customPage(Page<ApartmentItemVo> page, ApartmentQueryVo queryVo) {
        apartmentInfoMapper.customSelectPage(page,queryVo);
    }

    @Override
    public void customRemoveById(Long id) {
        //重要数据需要二次确认或者干脆不能删,非重要数据可以直接删,这里公寓关联的房间信息是重要数据,图片/配套/标签/杂费是非重要数据
        LambdaQueryWrapper<RoomInfo> roomWrapper = new LambdaQueryWrapper<>();
        roomWrapper.eq(RoomInfo::getApartmentId, id);
        long count = roomInfoService.count(roomWrapper);

        if (count > 0) {
            throw new LeaseException(ResultCodeEnum.DELETE_ERROR);
        }

        apartmentInfoMapper.deleteById(id);

        //中间表删除在saveOrUpdate()方法也使用了,可以提取
        //配套
        LambdaQueryWrapper<ApartmentFacility> facilityWrapper = new LambdaQueryWrapper<>();
        facilityWrapper.eq(ApartmentFacility::getApartmentId, id);
        apartmentFacilityService.remove(facilityWrapper);
        //标签
        LambdaQueryWrapper<ApartmentLabel> labelWrapper = new LambdaQueryWrapper<>();
        labelWrapper.eq(ApartmentLabel::getApartmentId, id);
        apartmentLabelService.remove(labelWrapper);
        //杂费
        LambdaQueryWrapper<ApartmentFeeValue> feeValueWrapper = new LambdaQueryWrapper<>();
        feeValueWrapper.eq(ApartmentFeeValue::getApartmentId, id);
        apartmentFeeValueService.remove(feeValueWrapper);
        //图片
        LambdaQueryWrapper<GraphInfo> graphInfoWrapper = new LambdaQueryWrapper<>();
        graphInfoWrapper.eq(GraphInfo::getItemId, id);
        graphInfoWrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT);
        graphInfoService.remove(graphInfoWrapper);

    }


}




